package com.tencent.welink.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by junchihe on 2018/11/26.
 */

public class CrontabUtil {
    private static final Logger logger = LogManager.getLogger(CrontabUtil.class);
    private ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(10);
    private static CrontabUtil _inst = new CrontabUtil();

    private CrontabUtil() {
        logger.debug("CrontabUtil init");
    }

    public static void addTaskInRate(Runnable cmd, int millsSec, boolean runRightNow) {
        logger.debug("add task");
        if(runRightNow) {
            try{
                cmd.run();
            }catch (Exception e) {
                logger.error(e);
            }
            _inst.newScheduledThreadPool.scheduleAtFixedRate(cmd, (long)millsSec, (long)millsSec, TimeUnit.MILLISECONDS);
        } else {
            _inst.newScheduledThreadPool.scheduleAtFixedRate(cmd, 0, (long)millsSec, TimeUnit.MILLISECONDS);
        }

    }

    public static void addTaskInRate(Runnable cmd, int initialDelay, int period) {
        logger.debug("add task at initialDelay");
        _inst.newScheduledThreadPool.scheduleAtFixedRate(cmd, (long)initialDelay, (long)period, TimeUnit.MILLISECONDS);
    }

    public static void shutdown(){
        _inst.newScheduledThreadPool.shutdown();
    }

    public static void main(String[] args) {
        Runnable command = new Runnable() {
            public void run() {
                CrontabUtil.logger.debug("thread is :{}  curtime: {}", Thread.currentThread(), Long.valueOf(System.currentTimeMillis()));
            }
        };
        logger.debug("=========== main go " + System.currentTimeMillis());

       // for(int i = 0; i < 3; ++i) {
            addTaskInRate(command, 10000, true);
      //  }

    }
}
